﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MDReader.Helper;
using MDReader.Services;
using Microsoft.Win32;

namespace MDReader.Control
{
    public partial class frmSetting : Form
    {
        public frmSetting(ILog log, ISettingService setting)
        {
            logger = log;
            settingMgr = setting;
            InitializeComponent();
        }

        private readonly ILog logger;
        private readonly ISettingService settingMgr;
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {

            if (chkDefaultEdit.Checked)
            {
                try
                {
                    string appPath = Application.ExecutablePath;
                    FileAssociation.Associate(".md", "MarkdownViewer", "Markdown File", appPath);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"修改文件关联时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            #region 保存设置值
            string ErrorMsg = settingMgr.Save();
            if (!string.IsNullOrEmpty(ErrorMsg))
            {
                MessageBox.Show(ErrorMsg, "保存设置时", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return;
            }
            #endregion
            this.DialogResult = DialogResult.OK;

        }

        private void frmSetting_Load(object sender, EventArgs e)
        {
            // 读取注册表获得.md文件默认编辑器，判断是不是自己
            try
            {
                RegistryKey userChoiceKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.md\UserChoice");
                if (userChoiceKey != null)
                {
                    string progId = userChoiceKey.GetValue("Progid").ToString();
                    if (progId == "MarkdownViewer")
                    {
                        chkDefaultEdit.Checked = true;
                    }
                    userChoiceKey.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"读取注册表时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            #region 按照设置列表生成选项
            foreach (var setting in this.settingMgr.ToList())
            {
                Panel p = setting.CreateEditorPanel(); // 创建控件并把当前设置值填入控件中
                if (p != null)
                    flowLayoutPanel1.Controls.Add(p);
            }
            #endregion
        }
    }

    public class FileAssociation
    {
        [DllImport("shell32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern void SHChangeNotify(uint wEventId, uint uFlags, IntPtr dwItem1, IntPtr dwItem2);
        public static void Associate(string extension, string progId, string description, string application)
        {
            RegistryKey key = Registry.ClassesRoot.CreateSubKey(extension);
            key.SetValue("", progId);
            key.Close();
            key = Registry.ClassesRoot.CreateSubKey(progId);
            key.SetValue("", description);
            key.CreateSubKey("DefaultIcon").SetValue("", application + ",0");
            key.CreateSubKey(@"Shell\Open\Command").SetValue("", "\"" + application + "\" \"%1\"");
            key.Close();
            SHChangeNotify(0x08000000, 0x0000, IntPtr.Zero, IntPtr.Zero);
        }
    }
}
